'''
@author: harumonia
@site: 
@datetime: 2020/3/14 20:36
@software: PyCharm
'''
from flask_admin.contrib.sqla import ModelView
from flask_login import current_user
from wtforms import TextAreaField
from wtforms.widgets import TextArea

from application.extensions import db
from application.utils.time_handler import get_now_datetime


class Course(db.Model):
    __tablename__ = 'course'
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='id')
    loginId = db.Column(db.BigInteger, db.ForeignKey('user.id'))
    courseName = db.Column(db.String(20), comment='课程名字')
    coursePrice = db.Column(db.Float, comment='课程价格')
    subhead = db.Column(db.String(255), comment='课程副标题')
    description = db.Column(db.Text, comment='课程说明')
    url = db.Column(db.String(100), comment='课程地址')
    create_date = db.Column(db.DateTime, comment='课程开始日期')
    status = db.Column(db.String(1), comment='课程状态')
    users = db.relationship('User',
                            backref=db.backref('course'))

    def __repr__(self):
        return str(self.id) + '.' + self.courseName


class CKEditor(TextArea):
    def __call__(self, field, **kwargs):
        c = kwargs.pop('class', '') or kwargs.pop('class_', '')
        kwargs['class'] = u'%s %s' % ('ckeditor', c)
        # field.name = 'ckeditor'
        # field.id = 'ckeditor'
        return super(CKEditor, self).__call__(field, **kwargs)


class CKEditorField(TextAreaField):
    widget = CKEditor()


class CourseView(ModelView):
    form_overrides = dict(description=CKEditorField)
    create_template = 'edit_article.html'
    edit_template = 'edit_article.html'
    form_excluded_columns = ['url', 'create_date', 'status']
    column_exclude_list = ['description']

    def on_model_change(self, form, Course, is_created):
        Course.loginId = current_user.id
        if is_created:
            Course.create_date = get_now_datetime()
            Course.status = '1'

    def on_model_delete(self, Article):
        Article.status = False
